# -*- coding: utf-8 -*-
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from celery import shared_task
import time
from django.utils import timezone
import json
import urllib2
import redis
from models import CoinHistory

# timezone = 'Asia/Shanghai'
r = redis.Redis(host='localhost',port=6379,db=0)
# max, min, cur, trend, trend_amount

@periodic_task(run_every=(crontab(minute='*/1')), name="xpr_deal", ignore_result=True)
def xpr_deal():
    ticker_url = "http://api.btc38.com/v1/ticker.php?c=xrp&mk_type=cny"
    ticker_request = request_head(ticker_url)
    ticker_data_raw = urllib2.urlopen(ticker_request).read()

    depth_url = "http://api.btc38.com/v1/depth.php?c=xrp&mk_type=cny"
    depth_request = request_head(depth_url)
    depth_data_raw = urllib2.urlopen(depth_request).read()

    try:
        ticker_dict = json.loads(ticker_data_raw)
        xpr_data = ticker_dict["ticker"]

        depth_dict = json.loads(depth_data_raw)
	bids = depth_dict["bids"]
        asks = depth_dict["asks"]
	buy_amount = sell_amount = 0
	for bid in bids:
            buy_amount += bid[1]
        for ask in asks:
            sell_amount += bid[1]
        now = timezone.now()

        r.set("xpr_high", xpr_data["high"])
        r.set("xpr_low", xpr_data["low"])
        r.set("xpr_last", xpr_data["last"])
        CoinHistory.objects.create(coin_type="xrp",
                                   price=xpr_data["last"],
                                   time=now,
                                   buy_amount=buy_amount,
                                   sell_amount=sell_amount)
        print("finished")
    except:
        print("except..")

@periodic_task(run_every=(crontab(minute='*/1')), name="all_coin_deal", ignore_result=True)
def all_coin_deal():
    url = "http://api.btc38.com/v1/ticker.php?c=all&mk_type=cny"
    request = request_head(url)
    data_raw = urllib2.urlopen(request).read()


    depth_url = "http://api.btc38.com/v1/depth.php?c=btc&mk_type=cny"
    depth_request = request_head(depth_url)
    depth_data_raw = urllib2.urlopen(depth_request).read()

    now = timezone.now()

    try:
        data_dict = json.loads(data_raw)
        btc_data = data_dict["btc"]["ticker"]


        depth_dict = json.loads(depth_data_raw)
	bids = depth_dict["bids"]
        asks = depth_dict["asks"]
	buy_amount = sell_amount = 0
	for bid in bids:
            buy_amount += bid[1]
        for ask in asks:
            sell_amount += bid[1]

        r.set("btc_high", btc_data["high"])
        r.set("btc_low", btc_data["low"])
        r.set("btc_last", btc_data["last"])

        CoinHistory.objects.create(coin_type="btc",
                                   price=btc_data["last"],
                                   time=now,
                                   buy_amount=buy_amount,
                                   sell_amount=sell_amount)
        print("finished")
    except:
        print("except..")


def request_head(url):
    request = urllib2.Request(url)
    request.add_header('User-Agent', 'fake-client')
    request.add_header('cache-control', 'no-cache');
    request.add_header('accept', '*/*');
    request.add_header('connection', 'keep-alive');
    return request

'''
@periodic_task(run_every=(crontab(hour=4, minute=15)), name="delete hislog", ignore_result=True)
def delete_his_task():
    pass
'''

'''
@shared_task(name="test_celery")
def test_celery():
    print("print task")
    for i in range(1, 10):
        time.sleep(1)
        celery_logger.info("test_celery in %s" % i)
'''
